package com.blog.zip.interceptor;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.blog.zip.bean.User;
import com.blog.zip.service.TokenService;
import com.blog.zip.util.TokenUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

//Struts
@Slf4j
public class AuthenticationInterceptor implements HandlerInterceptor {

    @Autowired
    TokenService tokenService;

    /**
     * 目标方法执行之前
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        //log.info("拦截的请求路径是{}", requestURI);
//        Object loginUser = request.getSession().getAttribute("loginUser");
//        request.setAttribute("msg", "please login in");
        Map<String,Object> map = new HashMap<>();
        String token = request.getHeader("B-Token");

        try{
            //log.info("生成的token是{}", token);
            DecodedJWT verify = TokenUtil.verify(token);
            map.put("state",200);
            map.put("msg","请求成功");
//            log.info("用户id：[{}]",verify.getClaim("id").asString());
//            log.info("用户名：[{}]",verify.getClaim("username").asString());
            return true;
        }catch (SignatureVerificationException e){
//            e.printStackTrace();
            map.put("msg","无效签名");
        }catch (TokenExpiredException e){
//            e.printStackTrace();
            map.put("msg","token过期");
        }catch (AlgorithmMismatchException e){
//            e.printStackTrace();
            map.put("msg","token算法不一致");
        }catch (Exception e){
//            e.printStackTrace();
            map.put("msg","程序执行出现异常");
            map.put("error",e);
        }
        map.put("state",-1);
        String json = new ObjectMapper().writeValueAsString(map);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(json);
        return false;
    }


    /**
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //System.out.println("POST");
        //HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    /**
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //System.out.println("AFTER");
        //HandlerInterceptor.super.afterCompletion(request, response, handler, ex);

    }
}
